import {Dictionary} from "../types/Types";
import SerializeForm from "./SerializeForm";

export function getFnName(callee: Function):string {

    let calleeStr=callee.toString(),
        _callee= calleeStr.replace(/[\s\?]*/g, ""),

        comb = _callee.length >= 50 ? 50 : _callee.length;

    _callee = _callee.substring(0, comb);

    let name = _callee.match(/^function([^\(]+?)\(/);

    if (name && name[1]) {

        return name[1];

    }

    let caller = callee.caller;
    if (caller === null)
        return calleeStr;

    let _caller = caller.toString().replace(/[\s\?]*/g, "");

    let last = _caller.indexOf(_callee),

        str = _caller.substring(last - 30, last);

    name = str.match(/var([^\=]+?)\=/);

    if (name && name[1]) {

        return name[1];

    }
    return calleeStr;

}

export function buildFullUrl(path:string) {
    if(path.indexOf("http")>-1)
        return path;
    var baseUrl = window.location.origin;
    if (!baseUrl) {
        baseUrl = window.location.protocol + "//" + window.location.host;
    }
    if (baseUrl.lastIndexOf("/") == baseUrl.length - 1) {
        baseUrl += "/";
    }
    return baseUrl + path;
}

function strToHex(input:string):string {
    if(isEmpty(input))
        return "";
    let hexArray=[];
    for(let i=0;i<input.length;i++){
        hexArray.push(input.charCodeAt(i).toString(16));
    }
    return hexArray.join("");
}

export function appendParamsToUrl(url:string, params:string) {
    if (url.indexOf("?") > 0) {
        url += "&";
    } else {
        url += "?";
    }
    return buildFullUrl(url)+params;
}

export function addExtendAgentToUrl(url:string,pluginType:string) {
    let extendAgentParams:string="pluginType="+pluginType+"&userAgent="+strToHex(navigator.userAgent);
    return appendParamsToUrl(url,extendAgentParams);
}

export function appendFormParamToUrl(url:string,formId:string|number=0) {
    let formElement:HTMLFormElement|null;
    if(typeof formId==='string'){
        formElement=document.forms.namedItem(<string>formId);
        if(!formElement)
            formElement=<HTMLFormElement>document.getElementById(formId);
    }else {
        formElement=document.forms[formId];
    }
    if(!formElement)
        return;
    const serialize=new SerializeForm(formElement);
    const urlEncodeParams=serialize.toString();
    return appendParamsToUrl(url,urlEncodeParams);
}

export function isEmpty(value: any) {
    return value===undefined||value===null||value==="";
}

export function safeToString(value:string|number|undefined|null):string {
    if(isEmpty(value))
        return "";
    return ""+value;
}

export function invokeFunction(funcName: string, context: any, args: any[]) {
    if(!funcName)
        return ;
    let params=args;
    if(!Array.isArray(params))
        params=[params];
    if (funcName.replace(/[\s\?]*/g, "").indexOf("function(") > -1) {
        let anonymousFunc = eval("(0," + funcName + ")");
        return anonymousFunc.apply(context,params);
    }
    let namespaces: string[] = funcName.split(".");
    let func: string | undefined = namespaces.pop();
    while (typeof func === undefined) {
        func = namespaces.pop();
    }
    for (let i: number = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    return context[<string>func].apply(context, params);
}

export function getBrowserFlag(): number {
    let userAgent: string = window.navigator.userAgent.toLowerCase();
    let flag: number = 0;

    if (containStr("edge")) {
        flag = 6;
    } else if (containStr("opera")) {
        flag = 1;
    } else if (containStr("firefox")) {
        flag = 2;
    } else if (containStr("chrome")) {
        flag = 5;
    } else if (containStr("safari")) {
        flag = 3;
    } else if (containStr("compatible") && containStr("msie") || containStr("trident")) {
        flag = 4;
    }
    return flag;

    function containStr(str: string) {
        return str && userAgent.indexOf(str) > -1;
    }
}

export function generateUUID():string {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
}

export function clientEnv():Dictionary{
    let clientEnv:Dictionary = {};
    let ua = navigator.userAgent.toLowerCase();
    let s;
    (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? clientEnv={browser:'ie',version:s[1]} :
        (s = ua.match(/msie ([\d\.]+)/)) ? clientEnv={browser:'ie',version:s[1]} :
            (s = ua.match(/edge\/([\d\.]+)/)) ? clientEnv={browser:'edge',version:s[1]} :
                (s = ua.match(/firefox\/([\d\.]+)/)) ?clientEnv={browser:'firefox',version:s[1]} :
                    (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? clientEnv={browser:'opera',version:s[1]}:
                        (s = ua.match(/chrome\/([\d\.]+)/)) ? clientEnv={browser:'chrome',version:s[1]} :
                            (s = ua.match(/version\/([\d\.]+).*safari/)) ? clientEnv={browser:'safari',version:s[1]} : 0;

    clientEnv.platform="Other";
    const isWin:boolean = (navigator.platform == "Win32")||(navigator.platform == "Win64") || (navigator.platform == "Windows");
    const isMac:boolean = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
    if (isMac) clientEnv.platform="Mac";
    const isUnix:boolean = (navigator.platform == "X11") && !isWin && !isMac;
    if (isUnix) clientEnv.platform="Unix";
    const isLinux:boolean = (String(navigator.platform).indexOf("Linux") > -1);
    if (isLinux) clientEnv.platform="Linux";
    if (isWin) {
        clientEnv.platform="Windows"
    }
    return clientEnv;
}


